package com.briup.shopadmin.service.impl;

import com.briup.shopadmin.common.GlobalException;
import com.briup.shopadmin.service.IFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileServiceImpl implements IFileService {
    @Value("${nginx.path}")
    private  String  nginxPath;
    @Override
    public String upload(String query, MultipartFile file) {
//        后端校验数据格式
        String filename = file.getOriginalFilename();
        String[] arr = filename.split("[.]");
        String fileType=arr[arr.length-1];
//        图片格式校验
        if (fileType.toLowerCase().equals("png")||fileType.toLowerCase().equals("jpg")){
            String  imgName= UUID.randomUUID().toString()+"."+fileType;
//            保存图片
            File destFile = new File(nginxPath + query + "/" + imgName);
            try {
                file.transferTo(destFile);
                return imgName;
            } catch (IOException e) {
                e.printStackTrace();
                throw  new GlobalException(51001,"图片写入失败");
            }

        }else {
            throw  new GlobalException(51002,"上传的图片数据格式不支持,目前仅支持png和jpg格式的图片");
        }

    }
}
